package com.example.myapplication1;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.myapplication1.utils.PreferenceManager;
import com.example.myapplication1.db.DatabaseHelper;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private PreferenceManager preferenceManager;
    private NavController navController;
    private AppBarConfiguration appBarConfiguration;
    private DatabaseHelper databaseHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate started");
        
        Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> {
            Log.e(TAG, "Uncaught exception", throwable);
        });
        
        try {




            Log.d(TAG, "Initializing PreferenceManager");
            preferenceManager = new PreferenceManager(this);

            // Initialize database
            Log.d(TAG, "Initializing DatabaseHelper");
            databaseHelper = new DatabaseHelper(this);
            if (!databaseHelper.isDatabaseExists()) {
                Log.d(TAG, "Creating new database");
                databaseHelper.getWritableDatabase();
            }

            // Check login status
            Log.d(TAG, "Checking login status");
            if (!preferenceManager.isLoggedIn()) {
                Log.d(TAG, "User not logged in, redirecting to LoginActivity");
                startLoginActivity();
                return;
            }

            Log.d(TAG, "Setting content view");
            // Set up the main layout
            setContentView(R.layout.activity_main);
            
            Log.d(TAG, "Setting up navigation");
            // Set up navigation
            setupNavigation();
            
        } catch (Exception e) {
            Log.e(TAG, "Fatal error in MainActivity", e);
            e.printStackTrace();
            startLoginActivity();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy called");
        if (databaseHelper != null) {
            databaseHelper.close();
        }
    }

    private void setupNavigation() {
        try {
            Log.d(TAG, "Getting NavHostFragment");
            // Get NavHostFragment
            NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.nav_host_fragment);
            
            if (navHostFragment == null) {
                Log.e(TAG, "NavHostFragment is null!");
                throw new IllegalStateException("NavHostFragment not found");
            }
            
            Log.d(TAG, "Getting NavController");
            // Get NavController
            navController = navHostFragment.getNavController();
            
            Log.d(TAG, "Setting up BottomNavigationView");
            // Set up BottomNavigationView
            BottomNavigationView bottomNav = findViewById(R.id.bottomNavigation);
            if (bottomNav == null) {
                Log.e(TAG, "BottomNavigationView is null!");
                throw new IllegalStateException("BottomNavigationView not found");
            }
            
            Log.d(TAG, "Configuring top level destinations");
            // Configure top level destinations
            appBarConfiguration = new AppBarConfiguration.Builder(
                    R.id.navigation_home,
                    R.id.navigation_cart,
                    R.id.navigation_profile
            ).build();

            // 修改为更简单的方式处理底部导航点击
            bottomNav.setOnItemSelectedListener(item -> {
                int itemId = item.getItemId();
                Log.d(TAG, "Bottom navigation item selected: " + itemId);
                
                try {
                    // 清除回退栈中的所有Fragment，直接导航到目标Fragment
                    if (itemId == R.id.navigation_home) {
                        navController.popBackStack();
                        navController.navigate(R.id.navigation_home);
                        return true;
                    } else if (itemId == R.id.navigation_cart) {
                        navController.popBackStack();
                        navController.navigate(R.id.navigation_cart);
                        return true;
                    } else if (itemId == R.id.navigation_profile) {
                        navController.popBackStack();
                        navController.navigate(R.id.navigation_profile);
                        return true;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "导航失败: " + e.getMessage());
                }
                return false;
            });
            
            Log.d(TAG, "Navigation setup completed successfully");
            
        } catch (Exception e) {
            Log.e(TAG, "Error setting up navigation", e);
            e.printStackTrace();
            startLoginActivity();
        }
    }

    private void startLoginActivity() {
        Log.d(TAG, "Starting LoginActivity");
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume called");
        // Check login status on resume
        if (!preferenceManager.isLoggedIn()) {
            startLoginActivity();
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        return NavigationUI.navigateUp(navController, appBarConfiguration)
                || super.onSupportNavigateUp();
    }
}